package org.example.util;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

import static org.example.constant.RedisConstant.*;

/**
 * redis生成全局唯一id
 */
@Component
public class OnlyId {

    private static StringRedisTemplate redisTemplate;

    public OnlyId(StringRedisTemplate stringRedisTemplate) {
        redisTemplate = stringRedisTemplate;
    }

    /**
     * 生成全局唯一id方法
     */
    public static Long nextId() {
        // 1.生成时间戳
        LocalDateTime now = LocalDateTime.now();
        long nowSecond = now.toEpochSecond(ZoneOffset.UTC);
        long timestamp = nowSecond - BEGIN_TIMESTAMP;
        // 2.生成序列号
        // 2.1.获取当前日期，精确到天
        String date = now.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
        // 2.2.自增长 key格式：icr:order:2023:05:21
        long count = redisTemplate.opsForValue().increment(ONLY_ID + date);
        // 3.拼接并返回，目的是让时间戳存放在32上，序列号在低32位
        return timestamp << COUNT_BITS | count;
    }
}
